import type { ConsultType, IllnessType } from '@/enums'
import type { IllnessData, PartialConsult } from '@/types/consult'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useConsultStore = defineStore(
  'cp-consult',
  () => {
    /** 问诊记录状态 */
    const consult = ref<PartialConsult>({})

    /** 订单id */
    const orderId = ref('')

    /**
     * 修改问诊类型
     * @param type 问诊类型
     */
    const setConsultType = (type: ConsultType) => {
      consult.value.type = type
    }

    /**
     * 修改极速问诊类型
     * @param type 极速问诊类型
     */
    const setIllnessType = (type: IllnessType) => {
      consult.value.illnessType = type
    }

    /**
     * 修改科室id
     * @param depId 科室id
     */
    const setDepId = (depId: string) => {
      consult.value.depId = depId
    }

    /**
     * 修改病情描述相关信息
     * @param illnessData 病情描述相关的数据
     */
    const setIllnessData = (illnessData: IllnessData) => {
      consult.value.illnessDesc = illnessData.illnessDesc
      consult.value.illnessTime = illnessData.illnessTime
      consult.value.consultFlag = illnessData.consultFlag
      consult.value.pictures = illnessData.pictures
    }

    /**
     * 修改患者id
     * @param patientId 患者id
     */
    const setPatientId = (patientId: string) => {
      consult.value.patientId = patientId
    }

    /**
     * 设置优惠券id
     * @param couponId 优惠券id
     */
    const setCouponId = (couponId: string) =>
      (consult.value.couponId = couponId)

    /**
     * 清空问诊记录
     */
    const clearConsult = () => {
      consult.value = {}
    }

    /**
     * 根据 id 删除图片
     * @param id 图片文件对象的 id
     */
    const delPicture = (id: string) => {
      // findIndex：找索引，找到了就是索引，找不到就是 -1
      // const i = consult.value.pictures?.findIndex((v) => v.id === id)
      // if (i !== undefined && i !== -1) {
      //   consult.value.pictures?.splice(i, 1)
      // }

      // 如果有图片数组
      if (consult.value.pictures) {
        // 就去找索引
        const i = consult.value.pictures.findIndex((v) => v.id === id)
        // 如果找到了索引
        if (i !== -1) {
          // 就去删图片
          consult.value.pictures.splice(i, 1)
        }
      }
    }

    return {
      consult,
      orderId,
      delPicture,
      setConsultType,
      setIllnessType,
      setDepId,
      setIllnessData,
      setPatientId,
      setCouponId,
      clearConsult
    }
  },
  // 要同步到本地，不然刷新就丢了
  { persist: true }
)

// import { useConsultStore } from '@/stores'
// const consultStore = useConsultStore()
// consultStore.consult
